import ttkbootstrap as ttk
from form.TestForm import TestForm


class Column:
    def __init__(self, field, label, sortable=False):
        self.field = field
        self.label = label
        self.sortable = sortable


class Grid:
    def __init__(self, root, data_model):
        self.root = root
        self.data_model = data_model
        self.columns = []

    def column(self, field, label=None, sortable=False):
        if not label:
            label = field.capitalize()
        column = Column(field, label, sortable)
        self.columns.append(column)
        return self

    def setup_ui(self):
        self.root.title("用户列表")

        # 创建 Treeview 展示用户列表
        column_fields = [col.field for col in self.columns]
        self.tree = ttk.Treeview(self.root, columns=column_fields, show="headings")
        for col in self.columns:
            self.tree.heading(col.field, text=col.label)
            self.tree.column(col.field, width=100)  # 设置列宽度
        self.tree.pack(pady=20)

        # 插入用户数据到 Treeview
        for item in self.data_model:
            values = [item.get(col.field, "") for col in self.columns]
            self.tree.insert("", "end", values=values)

        # 绑定选择事件
        self.tree.bind("<<TreeviewSelect>>", self.on_tree_select)

    def open_form_window(self, data):
        # 创建新的顶层窗口
        new_window = ttk.Toplevel(self.root)
        new_window.title("表单窗口")
        # 在新窗口中创建自定义表单实例，并传入用户数据
        form = TestForm(new_window, data)

    def on_tree_select(self, event):
        # 获取选中的行
        selected_item = self.tree.selection()
        if selected_item:
            item = self.tree.item(selected_item)
            # 获取该行的数据
            values = item["values"]
            user_data = {col.field: value for col, value in zip(self.columns, values)}
            # 打开表单窗口并传入用户数据
            self.open_form_window(user_data)


if __name__ == "__main__":
    # 创建主窗口
    root = ttk.Window(themename="flatly")

    # 模拟用户数据
    users = [
        {"id": 1, "name": "张三", "age": "20"},
        {"id": 2, "name": "李四", "age": "25"},
        {"id": 3, "name": "王五", "age": "30"}
    ]

    # 创建 Grid 实例
    grid = Grid(root, users)
    grid.column('id', 'ID', sortable=True)
    grid.column('name', '姓名')
    grid.column('age', '年龄')

    # 在所有列添加完毕后调用 setup_ui 方法
    grid.setup_ui()

    # 运行主循环
    root.mainloop()